// pages/video/video.js
const app = getApp()
var Parser = require('../../lib/dom-parser.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    switch_index: 0,
    info: '',
    video_list: '',
    video_count: 0,
    video_id: '',
    media_id: '',
    video_src: '',
    video_index: 0,
    auto_play: false,
    danmu_list: [],
    rateIndex: 0,
    rateArray: ['1.0', '1.25', '1.5', '2.0', '0.5', '0.8']
  },
  // 视频对象
  videoContext: null,
  // 选项卡切换
  changeSwitch: function(e) {
    // console.log(e)
    if (e.currentTarget.dataset.val == 1) {
      this.setData({
        switch_index: 1
      })
    } else {
      this.setData({
        switch_index: 0
      })
    }
  },
  changeTab: function(e) {
    //console.log(e)
    if (e.detail.current == 1) {
      this.setData({
        switch_index: 1
      })
    } else {
      this.setData({
        switch_index: 0
      })
    }
  },
  // 倍速播放
  changeRate: function(e) {
    var idx = e.detail.value
    var rate = this.data.rateArray[idx]
    this.setData({
      rateIndex: idx
    })
    this.videoContext.playbackRate(Number(rate))
  },
  // 切换集数
  changeVideo: function(e) {
    console.log('media:' + e.currentTarget.dataset.val)
    this.setData({
      auto_play: true,
      video_index: parseInt(e.currentTarget.id),
      media_id: e.currentTarget.dataset.val
    })
    this.getVideoURL()
    console.log('video_url:' + this.video_src)
  },
  // 播放完后自动切换下一集
  changeNext: function(e) {
    var that = this
    var index = this.data.video_index + 1
    console.log(index)
    if (index < this.data.video_count) {
      this.setData({
        auto_play: true,
        video_index: index,
        media_id: that.data.video_list[index].media_list.media['@attributes'].id
      })
      this.getVideoURL()
      console.log('video_url:' + this.video_src)
    } else {
      wx.showToast({
        icon: 'none',
        title: '最后一集播放完毕!',
      })
    }
  },
  // 视频播放时添加记录
  playVideo: function(e) {
    var that = this
    if (this.data.video_count > 1)
      app.addHistoryList({
        id: that.data.info.id,
        name: that.data.info.name,
        img: that.data.info.img_normal,
        mda_index: Number(that.data.video_index),
        mda_name: that.data.video_list[that.data.video_index]['@attributes'].name
      })
    else if (this.data.video_count == 1)
      app.addHistoryList({
        id: that.data.info.id,
        name: that.data.info.name,
        img: that.data.info.img_normal,
        mda_index: Number(that.data.video_index),
        mda_name: that.data.video_list['@attributes'].name
      })
    // 尝试查询弹幕
    try {
      if (this.data.danmu_list != []) {
        this.getDanmuList()
      }
    } catch (e) {
      console.log(e)
    }
  },
  // 获取弹幕
  getDanmuList: function() {
    //var xml = app.getDanmuList(this.data.video_id, this.data.video_index)
    var that = this
    var XMLParser = new Parser.DOMParser()
    var vid = this.data.video_id
    var idx = this.data.video_index
    var videolist = app.globalData.danmu_video //从视频列表中查询是否支持弹幕
    for (var i in videolist) {
      if (vid == videolist[i].id) {
        var cid = videolist[i].cid[idx]
        wx.request({
          url: 'https://comment.bilibili.com/' + cid + '.xml',
          method: 'GET',
          header: {
            'Content-Type': 'text/xml',
          },
          success: function(res) {
            //console.log(res.header)
            //console.log(res.errMsg)
            console.log(res.statusCode)
            console.log(res.header)
            var danmulist = []
            var xml = res.data
            ///////////////////////////////////////////////////
            // 　正则表达式获取弹幕
            var d = xml.match(/p=".*?</g)
            console.log(d[0].split(/[=".,<>]/))
            for (var i = 0; i < d.length; i++) {
              var attr = d[i].split(/[=".,<>]/)
              danmulist[i] = {
                text: attr[attr.length - 2],
                time: parseInt(attr[2]),
                color: '#' + parseInt(attr[6]).toString(16)
              }
            }
            
            ///////////////////////////////////////////////////////////////
            //对xml文件DOM处理获取弹幕
            // var doc = XMLParser.parseFromString(xml)    
            // var tag = doc.getElementsByTagName('d')
            // console.log(tag[0].firstChild.nodeValue)
            // var attr = tag[0].attributes[0].nodeValue.split(',')
            // for (var i = 0; i <= tag.length % 2000; i++) {
            //   var attr = tag[i].attributes[0].nodeValue.split(',')
            //   danmulist[i] = {
            //     text: tag[i].childNodes[0].nodeValue,
            //     time: parseInt(attr[0]),
            //     color: '#ffffff'
            //   }
            // }
            // console.log(danmulist)
            ///////////////////////////////////////////////////////////////////////
            that.setData({
              danmu_list: danmulist
            })
          }
        })
        break
      }
    }
  },
  // 播放状态测试
  waitPlay: function(e) {
    console.log("waiting...")
  },
  errorPlay: function(e) {
    console.log("error...")
  },
  pausePlay: function(e) {
    console.log("pause")
  },
  //获取视频链接
  getVideoURL: function() {
    var that = this
    wx.request({
      url: 'http://navod.scse.com.cn/nn_cms/nn_cms_view/std/n3_a_xml.php',
      data: {
        nns_nxtype: 'a',
        nns_tag: 29,
        nns_user_id: '',
        nns_device_id: '',
        nns_func: 'apply_play_video',
        nns_video_id: that.data.video_id,
        nns_video_type: 0,
        nns_media_id: that.data.media_id,
        nns_quality: '',
        nns_media_assets_id: '',
        nns_category_id: 1000,
        nns_video_index: that.data.video_index,
        nns_user_id: '',
        nns_token: '',
        nns_output_type: 'json'
      },
      method: 'GET',
      dataType: 'json',
      success: function(res) {
        console.log("getVideoURL=>")
        console.log(res)
        that.setData({
          video_src: res.data.data["@attributes"].url
        })

      },
      fail: function(res) {

      },
    })
  },
  getVideoInfo: function() {
    var that = this
    //var list = app.globalData.history_list
    //console.log(this.data.video_id)
    wx.request({
      url: 'http://navod.scse.com.cn//nn_cms/nn_cms_view/std/n3_a_xml.php',
      data: {
        nns_nxtype: 'a',
        nns_tag: 29,
        nns_user_id: '',
        nns_device_id: '',
        nns_func: 'get_video_info',
        nns_video_id: that.data.video_id,
        nns_video_type: 0,
        nns_user_id: '',
        nns_token: '',
        nns_output_type: 'json'
      },
      method: 'GET',
      success: function(res) {
        console.log('videoInfo=>')
        console.log(res)
        that.setData({
          info: res.data.data["@attributes"],
          video_list: res.data.data.index_list.index,
        })
        if (res.data.data.index_list.index.length == undefined) {
          that.setData({
            video_count: 1,
            media_id: res.data.data.index_list.index.media_list.media["@attributes"]
          })
        } else {
          that.setData({
            video_count: res.data.data.index_list.index.length,
            media_id: res.data.data.index_list.index['0'].media_list.media["@attributes"].id
          })
        }
        wx.setNavigationBarTitle({
          title: that.data.info.name,
        })

      },
      fail: function(res) {
        console.log(res)
      },
      complete: function(res) {

      }
    })
    this.getVideoURL()

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //  var that = this 
    if (options.id != undefined)
      this.setData({
        video_id: options.id,
      })
    if (options.index != undefined)
      this.setData({
        video_index: options.index
      })
    this.getVideoInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.videoContext = wx.createVideoContext('media')

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    console.log('reach')
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})